{% extends "templates/web.html" %}

{% block title %} {{_("Reset Password")}} {% endblock %}

{% block navbar %}{% endblock %}
{% block footer %}{% endblock %}
{% block head_include %}{% endblock %}
{% block page_content %}

<style>
	body {
		background-color: var(--subtle-fg);
		font-size: var(--text-base);
	}
	.container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		height: 100vh;
		max-width: 100vw;
		padding: 0;
		margin: 0;
	}
	/* styling the signup link */
	.portal-section, .pb-0{
		display: block;
	}
</style>

<div class="portal-container">
	<div class="portal-section head">
		<div class="title">{{ _("Reset Password") if frappe.db.get_default('company') else _("Set Password")}}</div>
	</div>
	<div class="portal-section pb-0">
		<form id="reset-password" style="width: 100%">
			<div class="form-group">
				<input id="old_password" type="password"
					class="form-control mb-4" placeholder="{{ _('Old Password') }}" autocomplete="current-password" required>
			</div>
			<div class="form-group">
				<div class="password-field">
					<input type="password" id="new_password"
						class="form-control mb-4" placeholder="{{ _('New Password') }}" autocomplete="new-password" required>
					<span class="password-strength-indicator indicator"></span>
					<svg class="field-icon password-icon" width="16" height="16" viewBox="0 0 16 16" fill="none"
						xmlns="http://www.w3.org/2000/svg">
							<use class="es-lock" href="#es-line-lock"></use>
					</svg>
					<span toggle="#new_password" class="toggle-password text-muted">{{ _('Show') }}</span>
				</div>
			</div>
			<div class="form-group">
				<div class="password-field">
					<input id="confirm_password" type="password"
						class="form-control mb-4" placeholder="{{ _('Confirm Password') }}" autocomplete="new-password" required>
					<svg class="field-icon password-icon" width="16" height="16" viewBox="0 0 16 16" fill="none"
						xmlns="http://www.w3.org/2000/svg">
							<use class="es-lock" href="#es-line-lock"></use>
					</svg>
					<span toggle="#confirm_password" class="toggle-password text-muted">{{ _('Show') }}</span>
				</div>
			</div>
			<p class="password-mismatch-message text-muted small hidden mt-2"></p>
			<p class='password-strength-message text-muted small mt-2 hidden'></p>
			<button type="submit" id="update" disabled = true style="cursor: not-allowed;"
				class="btn btn-primary btn-block btn-update">{{_("Confirm")}}</button>
		</form>
		{%- if not disable_signup -%}
			<div class="text-center sign-up-message">
				{{ _("Don't have an account?") }}
				<a href="/login#signup">{{ _("Sign up") }}</a>
			</div>
		{%- endif -%}
	</div>
</div>

<script>

frappe.ready(function() {
	// URL args
	const key = frappe.utils.get_url_arg('key');
	const password_expired = frappe.utils.get_url_arg('password_expired');
	// inputs, paragraphs and button elements
	const old_password = $('#old_password');
	const new_password = $('#new_password');
	const confirm_password = $('#confirm_password');
	const update_button = $('#update');
	const password_strength_indicator = $('.password-strength-indicator');
	const password_strength_message =$('.password-strength-message');
	const password_mismatch_message = $('.password-mismatch-message');
	// Info text
	const password_not_same_as_old_password = "{{ _('New password cannot be same as old password') }}";
	const password_mismatch = "{{ _('Passwords do not match') }}";
	const password_strength_message_success = "{{ _('Password is valid. 👍') }}";

	if(key) {
		old_password.parent().toggle();
	}

	if(password_expired) {
		$(".password-box").html("{{ _('The password of your account has expired.') }}");
	}

	$("#reset-password").on("submit", function() {
		return false;
	});

	new_password.on("keypress", function(e) {
		if(e.which===13) update_button.click();
	})

	$(".toggle-password").click(function() {
		let input = $($(this).attr("toggle"))

		if(input.attr("type") == "password") {
			input.attr("type", "text")
			$(this).text({{ _("Hide") | tojson }});
		} else {
			input.attr("type", "password")
			$(this).text({{ _("Show") | tojson }});
		}
	});

	update_button.click(function() {
		var args = {
			key: key || "",
			old_password: old_password.val(),
			new_password: new_password.val(),
			confirm_password: confirm_password.val(),
			logout_all_sessions: 1
		}
		if (!args.old_password && !args.key) {
			frappe.msgprint({
				title: "{{ _('Missing Value') }}",
				message: "{{ _('Please enter your old password.') }}",
				clear: true
			});
		}
		if (!args.new_password) {
			frappe.msgprint({
				title: "{{ _('Missing Value') }}",
				message: "{{ _('Please enter your new password.') }}",
				clear: true
			});
		}
		if (args.old_password === args.new_password) {
			frappe.msgprint({
				title: "{{ _('Invalid Password') }}",
				message: password_not_same_as_old_password,
			});
			password_strength_message.addClass('hidden');
			return;
		}

		if (args.new_password !== args.confirm_password) {
			password_mismatch_message.text(password_mismatch)
				.removeClass('hidden text-muted').addClass('text-danger');
			password_strength_message.addClass('hidden');
			return;
		}

		frappe.call({
			type: "POST",
			method: "frappe.core.doctype.user.user.update_password",
			btn: update_button,
			args: args,
			statusCode: {
				401: function() {
					$(".page-card-head .reset-password-heading").text("{{ _('Invalid Password') }}");
					frappe.msgprint({
						title: "{{ _('Invalid Password') }}",
						message: "{{ _('Your old password is incorrect.') }}",
						// clear any server message
						clear: true
					});
				},
				410: function({ responseJSON }) {
					const title = "{{ _('Invalid Link') }}";
					const message = responseJSON.message;
					$(".page-card-head .reset-password-heading").text(title);
					frappe.msgprint({ title: title, message: message, clear: true });
				},
				200: function(r) {
					$("input").val("");
					strength_indicator.addClass("hidden");
					strength_message.addClass("hidden");
					$(".page-card-head .reset-password-heading")
						.html("{{ _('Status Updated') }}");
					if(r.message) {
						frappe.msgprint({
							title: "{{ _('Password set') }}",
							message: "{{ _('Your new password has been set successfully.') }}",
							// password is updated successfully
							// clear any server message
							clear: true
						});
						setTimeout(function() {
							window.location.href = r.message;
						}, 2000);
					}
				}
			}
		});

		return false;
	});

	window.strength_indicator = password_strength_indicator;
	window.strength_message = password_strength_message;

	new_password.on('keyup', function() {
		window.clear_timeout();
		window.timout_password_strength = setTimeout(window.test_password_strength, 200);
	});

	$("#old_password, #new_password, #confirm_password").on("keyup paste", frappe.utils.debounce(function () {
		let common_conditions = new_password.val() && confirm_password.val() && new_password.val() === confirm_password.val()

		if (new_password.val() && old_password.val() === new_password.val()) {
			password_mismatch_message.text(password_not_same_as_old_password)
				.removeClass("hidden text-muted").addClass("text-danger");

			password_strength_message.addClass("hidden");
		}
		if ((new_password.val() || old_password.val) && old_password.val() !== new_password.val()) {
			password_mismatch_message.addClass("hidden");
			password_strength_message.removeClass("hidden");
			password_mismatch_message.text('')
		}

		if (new_password.val() === confirm_password.val() && old_password.val() !== new_password.val() ) {
			password_mismatch_message.addClass("hidden");
			password_strength_message.removeClass("hidden");
		}
		if (confirm_password.val() &&  new_password.val() !== confirm_password.val()) {
			password_mismatch_message.text(password_mismatch)
				.removeClass("hidden text-muted").addClass("text-danger");
			password_strength_message.addClass("hidden");
		}
		if ((key || (!key && old_password.val() )) && common_conditions ) {
			update_button.prop("disabled", false).css("cursor", "pointer");
		}
		else {
			update_button.prop("disabled", true).css("cursor", "not-allowed");
		}
		},500)
	)

	window.test_password_strength = function() {
		window.timout_password_strength = null;

		var args = {
			key: key || "",
			old_password: old_password.val(),
			new_password: new_password.val()
		}

		if (!args.new_password) {
			set_strength_indicator('grey', {'warning': "{{ _('Please enter the password') }}" });
			return;
		}

		return frappe.call({
			method: 'frappe.core.doctype.user.user.test_password_strength',
			args: args,
			callback: function(r) {
				console.log(r.message);
			},
			statusCode: {
				401: function() {
					$('.page-card-head .reset-password-heading')
						.text("{{ _('Invalid Password') }}");
				},
				200: function(r) {
					if (r.message) {
						var score = r.message.score,
							feedback = r.message.feedback;

						if (!feedback) {
							return;
						}

						feedback.score = score;

						if (feedback.password_policy_validation_passed) {
							set_strength_indicator('green', feedback);
						}else{
							set_strength_indicator('red', feedback);
						}
					}
				}
			}

		});
	};

	window.set_strength_indicator = function(color, feedback) {
		var message = [];
		feedback.help_msg = "";
		if(!feedback.password_policy_validation_passed){
			feedback.help_msg = "<br>" + "{{ _('Hint: Include symbols, numbers and capital letters in the password') }}";
		}
		if (feedback) {
			if(!feedback.password_policy_validation_passed){
				if (feedback.suggestions && feedback.suggestions.length) {
					message = message.concat(feedback.suggestions);
				} else if (feedback.warning) {
					message.push(feedback.warning);
				}
				message.push(feedback.help_msg);

			} else {
				message.push(password_strength_message_success);
			}
		}
		password_mismatch_message.addClass('hidden');

		strength_message.html(message.join(' ') || '').removeClass('hidden');
	}

	window.clear_timeout = function() {
		if (window.timout_password_strength) {
			clearTimeout(window.timout_password_strength);
			window.timout_password_strength = null;
		}
	};
});
</script>

{% endblock %}

{% block style %}
<style>
	body {
		background-color: var(--bg-color);
	}

	.password-strength-indicator {
		float: right;
		padding: 15px;
		margin-top: -38px;
		margin-right: -7px;
	}

	.password-strength-message {
		margin-top: -10px;
	}
	{% include "templates/styles/card_style.css" %}
</style>
{% endblock %}
